import os
import cgi

from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

# Increments counter in the database 
def increment_counter(key, amount):
  obj = db.get(key)
  obj.counter += amount
  obj.put()
  return obj.counter

class Link(db.Model):
    title = db.StringProperty(required=True)
    added_by = db.UserProperty()
    added_on = db.DateTimeProperty(auto_now_add=True)
    url = db.StringProperty(required=True)
    number = db.IntegerProperty()
    hash = db.StringProperty()
    
class Generator(db.Model):
    counter = db.IntegerProperty()
    
class BaseHandler(webapp.RequestHandler):
    def template_path(self, filename):
        return os.path.join(os.path.dirname(__file__), filename)
    
    def render_template(self, filename, title, template_values):
        user = users.get_current_user()
        template_values.setdefault('user', user)
        if user:
            login_url = users.create_logout_url(self.request.uri)
        else:
            login_url = users.create_login_url(self.request.uri)
        template_values.setdefault('login_url', login_url)
        template_values.setdefault('title', title)
        self.response.out.write(template.render(self.template_path(filename), template_values)) 

class MainPage(BaseHandler):
    def get(self):
        links = Link.all().order('-added_on')
        template_values = {
          'links': links,
        }
        self.render_template('index.html', 'Browse Links', template_values)

class AdminPage(BaseHandler):
    def get(self):
        do_reset = self.request.get('reset')
        if do_reset == True:
            Link.all().delete();
        self.render_template('admin.html', 'Administration', {})
        
class AddNewLink(BaseHandler):
    def get(self):
        self.render_template('linkform.html', 'Add Link', {})
        
    def post(self):
        #TODO: check for duplicates

        #Get new integer number
        q = db.GqlQuery("SELECT * FROM Generator")
        gen = q.get()
        if gen:
            num = db.run_in_transaction(increment_counter, gen.key(), 1)
        else:
            gen = Generator(counter=1).put();
            num = 1
        #TODO: Validation
        Link(url=cgi.escape(self.request.get('url')),
             title=self.request.get('title'), 
             added_by=users.get_current_user(),
             number=num
             ).put()
        self.redirect('/')
        
application = webapp.WSGIApplication([('/', MainPage),
                                      ('/new', AddNewLink),
                                      ('/manage', AdminPage),
                                      ], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
